package com.tunnel.client.tcp;

import java.util.Set;

import com.tunnel.client.task.TcpTask;
import com.tunnel.client.task.TcpTaskManager;
import com.tunnel.client.tunnel.TunnelChannelHandlerContextManager;
import com.tunnel.common.tunnel.TunnelDataQueue;
import com.tunnel.common.tunnel.TunnelDataQueueManager;
import com.tunnel.common.util.CollectionUtil;
import com.tunnel.common.util.LogUtil;

import io.netty.channel.ChannelHandlerContext;

public class TcpDataReceiverListener extends Thread{
	
	@Override
	public void run() {
		while(true){
			try {
				Thread.sleep(1);//防止cpu饱和
			} catch (Exception e) {}
			ChannelHandlerContext ctx = TunnelChannelHandlerContextManager.getChannelHandlerContext();
			if(ctx == null){
				continue;
			}
			
			Set<String> connectionIdSet = TcpTaskManager.getConnectionIdSet();
			if(CollectionUtil.isNotEmpty(connectionIdSet)){
				for(String connectionId:connectionIdSet){
					try {
						TcpTask task = TcpTaskManager.getTask(connectionId);
						if(task == null || task.isStop()){
							continue;
						}
						
						int len = task.available();
						if(len <= 0){
//							try {
//								task.sendUrgentData();// 发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信
//							} catch (Exception e) {
//								String error = e.getMessage() == null ? "connection "+task.getIpAndPort().getIp()+":"+task.getIpAndPort().getPort()+" closed":e.getMessage();
//								task.closeTcpConnection("tcp data receive listening,"+error);
//							}
							continue;//继续下一个
						}
						
						// 限定下数据包大小
						byte[] data = new byte[len < TunnelDataQueue.ITEM_SIZE() ? len : TunnelDataQueue.ITEM_SIZE()];
						task.read(data);

						// 往sever端回传数据
						TunnelDataQueueManager.commitData(task, TunnelDataQueueManager.TCP_DATA_MSG, ctx,
								task.getConnectionIdBytes(), data);


						/*try {
							//根据消息队列的窗口期作为休息参考，单task下保证窗口期不过多的把数据提交给队列
							Thread.sleep(TunnelDataQueue.ITEM_SEND_DELAY_TIME);
						} catch (Exception e) {}*/
					} catch (Exception e) {
						LogUtil.error(e);
					}
				}
				
			}
		}
	}
	
}
